<template>
  <a-page-header
    title="会员权益"
    @back="() => $router.back()"
    style="padding: 10px 24px"
  >
    <template #subTitle>
      <div class="tile_content">
        <div :style="{ color: isTimeExpired ? 'red' : '#00000073' }">
          {{ subTitle }}
        </div>
      </div>
    </template>
  </a-page-header>

  <!-- <div class="title">
    <a-button type="link" @click="clickFn">
      <search-outlined />
      消耗规则</a-button
    >
  </div> -->

  <div class="content_left">
    <span style="margin-right: 5px"> 当前剩余: </span>
    {{ currentPoint }}{{ point_coin_unit }}{{ point_coin_alias }}

    <question-circle-outlined
      @click="clickFn"
      style="margin-left: 5px; cursor: pointer"
    />
  </div>
  <div class="member_benefits">
    <div
      class="right-arrow"
      v-if="benefitsList?.length && showArrow"
      @click="rightScroll"
    >
      <right-outlined />
    </div>
    <div
      class="left-arrow"
      v-if="benefitsList?.length && showArrow"
      @click="leftScroll"
    >
      <left-outlined />
    </div>

    <div
      class="benefits_con"
      id="benefitsCon"
      v-if="benefitsList?.length"
      :class="{ 'flex-row-reverse': is_dickerH }"
    >
      <div
        class="benefits_item"
        v-for="(item, index) in benefitsList"
        :key="index"
      >
        <div class="top_bar">
          <div class="benefits_name">{{ item.name }}</div>
          <div class="benefits_desc">{{ item.introduction }}</div>
        </div>

        <div class="pay_money">
          ￥<span style="font-size: 36px; font-weight: bold">{{
            item.is_dicker == 1 ? '?': item.money 
          }}</span>
        </div>
        <a-button
          v-if="item.is_dicker == '0'"
          type="primary"
          @click="openShipModal(item)"
          class="status_btn"
          :style="getBgColor(item.can_pay)"
          style="border: none"
          :loading="payLoading"
          :class="item.can_pay == 0 ? 'status_btn_disabled' : ''"
          >{{ item.is_open == 1 ? "续费" : "立即开通" }}</a-button
        >

        <a-button
          v-if="item.is_dicker == '1'"
          type="primary"
          @click="openwm"
          class="status_btn"
          :style="getBgColor(item.can_pay)"
          style="border: none"
          >立即咨询</a-button
        >

        <div class="content_box">
          <div class="props_con" v-if="item.content?.length">
            <div
              class="props_item"
              v-for="(props_item, props_index) in item.content"
              :key="props_index"
              :style="{ fontWeight: props_index < 3 ? '700' : 'normal' }"
            >
              {{ props_item }}
            </div>
          </div>

          <div
            v-if="item.msg"
            style="
              margin-top: 5px;
              display: flex;
              justify-content: center;
              align-items: center;
            "
          >
            <span class="red-bd">赠送</span>
            {{ item.msg }}
          </div>
        </div>
      </div>
    </div>
    <div class="no_data" v-else>
      <a-empty>
        <template #description> 暂无数据 </template>
      </a-empty>
    </div>
    <memberShip
      :rechargeData="rechargeData"
      :visible="showMemberShip"
      @close="closeMemberShip"
    />

    <AddTeam
      :visible="addTeamVisible"
      @onClose="addTeamVisible = false"
      @success="addTeamSuccess"
      :business="isBusiness"
    />

    <a-modal
      :title="'选择' + (showMemberBusiness ? '企业' : '团队')"
      :width="500"
      :visible="showMemberVisible"
      @cancel="showMemberVisible = false"
      :footer="false"
      centered
      :zIndex="1002"
    >
      <team-slider
        @addTeam="addTeam"
        :team="showMemberTeam"
        :business="showMemberBusiness"
        height="400px"
        @change="onTeamChange"
      ></team-slider>
    </a-modal>

    <a-modal
      :dialogStyle="{
        top: '500px',
      }"
      :footer="null"
      :closable="false"
      :width="340"
      v-model:visible="visibleXuan"
      @ok="handleOk"
    >
      <div class="model-v">
        <img
          class="model-img"
          :src="configData.service_qrcode"
        />
      </div>
      <div class="model-T">微信扫码咨询客服</div>
    </a-modal>
  </div>

  <Ruletable @handleOk="handleOks" :subTitle="subTitle" ref="RuletableRef">
  </Ruletable>
</template>

<script>
import {
  defineComponent,
  ref,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  nextTick,
  onMounted,
  onUnmounted,
} from "vue";
import memberShip from "../shotstack/PersonalCenter/modules/memberShip.vue";
import utils from "../../common/utils/utils";
import request from "../../common/utils/request";
import AddTeam from "../../components/AddTeam/index.vue";
import TeamSlider from "@/components/TeamSlider/index.vue";
import Ruletable from "./modules/Ruletable.vue";
import store from "@/store";
import {
  RightOutlined,
  LeftOutlined,
  SearchOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import { useRoute } from "vue-router";
import { message } from "ant-design-vue";
import _ from "lodash";

import { isNumber } from "@/common/utils/is";

export default defineComponent({
  name: "memberBenefits",
  components: {
    memberShip,
    AddTeam,
    TeamSlider,
    RightOutlined,
    LeftOutlined,
    Ruletable,
    SearchOutlined,
    QuestionCircleOutlined,
  },
  setup() {
    const state = reactive({
      baseurl: "https://cos.kuaijingai.com",
      showMemberShip: false,
      benefitsList: [],
      rechargeData: {},
      addTeamVisible: false,
      showMemberVisible: false,
      teamList: [],
      ercodeVisible: false,
      scrollLeftArrActive: false,
      isBusiness: 0,
      showMemberTeam: false,
      showMemberBusiness: false,
      subTitle: "",
      showArrow: false,
      loading: false,
      payLoading: false,
      is_dickerH: false,
      visibleXuan: false,
      RuletableRef: null,
      currentPoint: 0,
      point_coin_unit: "",
      point_coin_alias: "",
      packagePrompt: "",
      configData: {}
    });

    const openwm = () => {
      state.visibleXuan = true;
    };

    // 套餐是否过期
    const isTimeExpired = computed(() => {
      const expireDate = new Date(store.getters?.versionInfo.expire_time);
      const currentDate = new Date();
      return currentDate > expireDate;
    });

    const getBenefitsList = () => {
      request.get("/work_ai", "/user/shotstack/package/list").then((res) => {
        console.log(res);
        state.benefitsList = res.result.map((item) => ({
          ...item,
          msg: "",
        }));

        state.benefitsList.forEach((item) => {
          if (item.point_coin.value !== 0) {
            item.msg = item.point_coin.value + "个" + item.point_coin.alias;
          }
        });

        // 分离出 is_dicker 等于 '1' 的元素
        // const dickerItems = state.benefitsList.filter(
        //   (item) => item.is_dicker === 1
        // );

        // 移除这些元素
        // state.benefitsList = state.benefitsList
        //   .filter((item) => item.is_dicker !== 1)
        //   .reverse();
        // 将 is_dicker 等于 '1' 的元素追加到数组末尾
        // state.benefitsList.unshift(...dickerItems);
        state.subTitle = res?.prompt;
        // 检查是否包含议价套餐
        // let foundDickerOne = state.benefitsList.some(
        //   (item) => item.is_dicker === 1
        // );
        // if (foundDickerOne) {
        //   state.is_dickerH = true;
        // }
      });
    };

    getBenefitsList();

    const closeMemberShip = () => {
      state.showMemberShip = false;
      state.rechargeData = {};
      getBenefitsList();
      store.dispatch("GetClipRoleList");
    };
    const openShipModal = async (item) => {
      if (state.loading) {
        return;
      }
      state.loading = true;
      if (item.can_pay == 0) return;
      const villageInfo = await store.dispatch("GetVillageInfo");
      if (!utils.getCurrentTeam()) {
        state.showMemberVisible = true;
        return;
      }
      state.payLoading = true;
      request
        .post("/work_ai", "/user/shotstack/order/tmpPayOrder", {
          from: "ai",
          package_id: item.id,
          team_id: utils.getCurrentTeam(),
          village_id: villageInfo ? villageInfo.id : 0,
        })
        .then((res) => {
          if (res?.pay_status === "success") {
            message.success("操作成功");
            state.loading = false;
            state.rechargeData = {};
            getBenefitsList();
            store.dispatch("GetClipRoleList");
            return;
          }
          state.payLoading = false;
          state.showMemberShip = true;
          state.rechargeData["option"] = {};
          state.rechargeData["option"]["money"] = item.money ? item.money : "0";
          state.rechargeData["order_id"] = res.order_id;
          state.rechargeData["payUrl"] =
            item.payUrl + "&tmp_order_id=" + res.order_id;
          state.loading = false;
        })
        .catch(() => {
          state.payLoading = false;
          state.loading = false;
        })
        .finally(() => {
          state.payLoading = false;
          state.loading = false;
        });
    };

    const addTeamSuccess = () => {
      state.addTeamVisible = false;
    };

    const getConfig = () => {
      // 优先从仓库取
      const work_ai_config = store.state?.shotstack?.work_ai_config;
      if (!!work_ai_config) {
        state.configData = JSON.parse(JSON.stringify(work_ai_config));
        return;
      }
      request.get("/work_ai", "/config").then((res) => {
        state.configData = res.list;
      });
    };


    getConfig()

    const addTeam = (is_business) => {
      state.addTeamVisible = true;
      state.isBusiness = is_business;
    };

    const onTeamChange = async (team) => {
      state.showMemberVisible = false;
    };

    const rightScroll = () => {
      let dom = document.getElementById("benefitsCon");
      if (dom.scrollLeft >= dom.scrollWidth - dom.offsetWidth) return;
      dom.scrollLeft += 330;

      console.log(dom.offsetWidth, dom.scrollWidth, dom.scrollLeft);
    };

    const leftScroll = () => {
      let dom = document.getElementById("benefitsCon");

      if (state.is_dickerH == false) {
        if (dom.scrollLeft == 0) return;
      }
      dom.scrollLeft -= 330;
    };

    const showArr = () => {
      let timeout = setTimeout(() => {
        let dom = document.getElementById("benefitsCon");
        if (dom?.scrollWidth - dom?.offsetWidth > 0) {
          state.showArrow = true;
        } else {
          state.showArrow = false;
        }
        clearTimeout(timeout);
      }, 500);
    };

    showArr();

    onMounted(() => {
      window.addEventListener("resize", showArr, true);
    });

    onUnmounted(() => {
      window.removeEventListener("resize", showArr);
    });
    const route = useRoute();
    const getBgColor = (can_pay) => {
      let normalBgColor = {
        background: `linear-gradient(90deg, rgb(119, 174, 250), rgb(84, 119, 255))`,
      };
      let disabledBgColor = {
        background: `linear-gradient(90deg, rgb(119, 174, 250), rgb(84, 119, 255))`,
      };
      if (route.path.includes("socialMedia")) {
        normalBgColor.background = `linear-gradient(90deg, rgb(119, 174, 250), rgb(84, 119, 255))`;
        disabledBgColor.background = `linear-gradient(90deg, rgb(119, 174, 250), rgb(84, 119, 255))`;
        // disabledBgColor.background = `linear-gradient(90deg, #77aefa, #5477ff)`
      }
      return can_pay ? normalBgColor : disabledBgColor;
    };

    const clickFn = () => {
      state.RuletableRef.showModal();
    };

    const init = async () => {
      const res = await request.get(
        "/work_ai",
        "/user/consume/consumptionPoint/rule",
        {
          isShotStack: "1",
        }
      );

      console.log(res, "基础渲染的值");

      // dataSource.value = res.result.content;
      state.currentPoint = res.result.currentPoint;
      state.point_coin_unit = res.point_coin_unit;
      state.point_coin_alias = res.point_coin_alias;
      state.packagePrompt = res.result.packagePrompt;
    };

    init();

    const handleOks = () => {};
    return {
      ...toRefs(state),
      closeMemberShip,
      openShipModal,
      addTeamSuccess,
      addTeam,
      rightScroll,
      leftScroll,
      showArr,
      getBgColor,
      openwm,
      clickFn,
      handleOks,
      isTimeExpired,
      isNumber,
    };
  },
});
</script>

<style lang="less" scoped>
.member_benefits {
  width: 100%;
  position: relative;
  display: flex;
  align-items: center;
  // flex-direction: column;
  padding-left: 20px;

  .right-arrow {
    position: absolute;
    top: 50%;
    right: 15px;
    z-index: 11;
    transform: translateY(-84%);
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    background: #ffffff;
    color: #2878ff;
    font-size: 20px;
    box-shadow: 0 0 18px #2878ff4d;
    border-radius: 50%;
    cursor: pointer;
    opacity: 0;
    transition: 0.3s ease;
  }

  .left-arrow {
    position: absolute;
    top: 50%;
    left: 15px;
    z-index: 11;
    transform: translateY(-84%);
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    background: #ffffff;
    color: #2878ff;
    font-size: 20px;
    box-shadow: 0 0 18px #2878ff4d;
    border-radius: 50%;
    cursor: pointer;
    opacity: 0;
    transition: 0.3s ease;
  }

  &:hover {
    .right-arrow {
      opacity: 1;
    }

    .left-arrow {
      opacity: 1;
    }
  }

  .no_data {
    width: 100%;
    height: calc(100vh - 200px);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .benefits_con {
    display: flex;
    width: 98%;
    overflow: scroll;
    flex-shrink: 0;

    &::-webkit-scrollbar {
      width: 0;
      height: 0;
    }

    .benefits_item {
      min-width: 287px;
      max-width: 300px;
      padding-bottom: 60px;
      margin: 20px;
      background: #ffffff;
      box-shadow: 0px 0px 27px 0px rgba(134, 138, 139, 0.14);
      border-radius: 10px;
      display: flex;
      flex-direction: column;
      align-items: center;

      .top_bar {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 96px;
        background: #f8fbff;
        border-radius: 10px 10px 0px 0px;

        .benefits_name {
          font-size: 22px;
          font-family: PingFang SC;
          font-weight: 800;
          color: #333333;
          width: 80%;
          text-align: center;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .benefits_desc {
          font-size: 12px;
          font-family: PingFang SC;
          font-weight: 800;
          color: #fe7b42;
          margin-top: 5px;
          width: 80%;
          text-align: center;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .pay_money {
        margin-top: 10px;
        font-size: 22px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #ff3400;
      }

      .status_btn_disabled {
        margin-top: 10px;
        width: 189px;
        height: 44px;
        background: linear-gradient(
          90deg,
          rgb(119, 174, 250),
          rgb(84, 119, 255)
        );
        // background: linear-gradient(90deg, #ff574a, #fdb63b);
        opacity: 0.43;
        border-radius: 22px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 18px;
        font-family: Source Han Sans CN;
        font-weight: 800;
        color: #ffffff;
        cursor: pointer;
      }

      .status_btn {
        margin-top: 10px;
        width: 189px;
        height: 44px;
        background: linear-gradient(90deg, #ff574a, #fdb63b);
        border-radius: 22px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 18px;
        font-family: Source Han Sans CN;
        font-weight: 800;
        color: #ffffff;
        cursor: pointer;
      }

      .props_con {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 0 50px;

        .props_item {
          font-size: 14px;
          font-family: PingFang SC;
          font-weight: 400;
          color: #000000;
          margin-top: 10px;
          width: 100%;
          text-align: center;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .horizantal_line {
        width: calc(100% - 40px);
        height: 2px;
        background: #eeeeee;
        margin: 30px 0;
      }

      .create_fun {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 0 50px;

        .fun_name {
          font-size: 16px;
          font-family: PingFang SC;
          font-weight: 600;
          color: #000000;
        }

        .fun_item {
          width: 100%;
          margin-top: 10px;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .left_label {
            font-size: 14px;
            font-family: PingFang SC;
            font-weight: 400;
            color: #000000;
            width: 50%;
            text-align: center;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .right_icon {
          }
        }
      }
    }
  }
}

.flex-row-reverse {
  flex-direction: row-reverse !important;
}

.model-v {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  margin-top: 20px;
}

.model-img {
  width: 200px;
  height: 200px;
}

.model-T {
  font-size: 14px;
  text-align: center;
  color: rgb(153, 153, 153);
}

.Allin_Qu {
  margin-left: 15px;
}

.red-text {
  color: red !important;
}

.tile_content {
  width: 1400px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  width: 100%;
  padding: 0px 37px 0 20px;
  display: flex;
  justify-content: flex-end;
}

.red-bd {
  color: #e75757;
  background-color: #ffefee;
  padding: 0 2px 0 2px;
  font-size: 14px;
}

.content_box {
  width: 100%;
  height: 125px;
}

.content_left {
  margin-left: 20px;
  font-size: 16px;
}
</style>
